/*
* @Date: 2021/2/27
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import Icon from '../Icon';
import './index.scss';

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: 'none',
    };
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.addEventListener('touchstart', e => {
      if (this.myRef.current.scrollTop !== 0) {
        return;
      }
      this.beginPagY = e.touches[0].pageY;
      this.distance = 0;
      // e.preventDefault();
    });
    this.myRef.current.addEventListener('touchmove', e => {
      if (this.myRef.current.scrollTop !== 0) {
        return;
      }
      this.currentPageY = e.touches[0].pageY;
      const distance = this.currentPageY - this.beginPagY;
      console.log('distance====>', distance);
      this.distance = distance;
      if (distance < 0 || distance > 120) {
        return;
      }
      if (distance > 60) {
        this.setState({
          status: 'pulling',
        });
      } else {
        this.setState({
          status: 'none',
        });
      }
      console.log('distance22====>', distance);
      e.preventDefault();
      this.myRef.current.style.transform = `translateY(${distance}px)`;
    });
    this.myRef.current.addEventListener('touchend', () => {
      this.myRef.current.style.transition = `.2s`;
      const { onLoading } = this.props;
      if (this.distance >= 60) {
        this.setState({
          status: 'loading',
        }, () => {
          this.myRef.current.style.transform = 'translateY(20px)';
        });
        onLoading && onLoading().then(() => {
          this.setState({
            status: 'none',
          }, () => {
            this.myRef.current.style.transform = 'translateY(0)';
            setTimeout(() => {
              this.myRef.current.style.transition = ``;
            }, 200);
          })
        });
      }
    });
  }

  render() {
    const { children, style = {} } = this.props;
    const { status } = this.state;
    return (
      <div ref={this.myRef} className="pull-down-content" style={style}>
        <div className={`pull-down-tip pull-down-status-${status}`}>
          <Icon type="refresh" />
          { status === 'pulling' && '释放刷新' }
          { status === 'loading' && '正在刷新' }
        </div>
        { children }
      </div>

    )
  }
}
